package net.springmvc11_12.controller;

import net.springmvc11_12.entity.Stu;
import net.springmvc11_12.service.StuService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
@ResponseBody
public class MyController {

    @GetMapping("my")
    public String my() {
        int a = 10 / 0;
        return "hh";
    }

    @GetMapping("interceptor")
    public String interceptor() {
        System.out.println("放行了，不会进入拦截器");
        return "hh";
    }

    @Autowired
    private StuService stuService;

    @GetMapping("login")
    public String login(@RequestParam String name,
                        @RequestParam String sn,
                        HttpSession session) {

        Stu stu = stuService.login(name, sn);
        if (stu != null) {
            session.setAttribute("stu", stu);
            return "hh";
        }
        return "login";
    }

    @PostMapping("upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file,
                         HttpSession session) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String realPath = session.getServletContext().getRealPath("/");
        System.out.println(realPath);
        File file1 = new File(realPath, originalFilename);
        file.transferTo(file1);
        return file1.getAbsolutePath();
    }

    @GetMapping("filedown")
    public void filedown(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        File file = new
                File(request.getSession().getServletContext().getRealPath("/"), "数据库连接须知.txt");
        System.out.println("文件：" + file.getAbsolutePath());
        byte[] data = FileUtils.readFileToByteArray(file);
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-disposition", "attachment;filename=" + new
                String(file.getName().getBytes("UTF-8"), "ISO8859-1"));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.getOutputStream().write(data);
    }
}
